/**
 * @file 角色数据权限范围
 * @date 2025/11/15 15:51:35
 * @author lyqjob@yeah.net
 */

import {  memo, useState, useEffect ,useImperativeHandle,forwardRef,useCallback,useMemo } from 'react';
import { Card, Tree, Form, Input ,Select,Empty} from 'antd';
import { adminApi } from '@/services/admin';

const DataPermission = forwardRef((props,ref) => {
    const { is_edit , access_type, scope ,curstom_ids} = props;
    const [form] = Form.useForm();

    const [rawTreeData, setRawTreeData] = useState([]); // 保存原始部门数据
    const [checkedKeys, setCheckedKeys] = useState([]);// 选中的部门id
    const [isCustomScope, setIsCustomScope] = useState(false);// 是否自定义数据范围
    

    useEffect(() => {

        getDepartmentList();

        if(access_type !== 'add'){

            form.setFieldsValue({
                data_scope: scope
            })

           
            if(scope === 5 && curstom_ids){
                const list = handleCustomScopeData(curstom_ids)
                setCheckedKeys(list)
                setIsCustomScope(true)
            }
        }
    }, [access_type,scope,curstom_ids,form,is_edit]);


    // 数据转换 - 参考父组件的convertTreeData实现
    const transformTreeData = useCallback((data, currentCheckedKeys = [], editMode = false) => {
        if (!data || data.length === 0) {
            return [];
        }
        const convertNode = (item) => {
            const isChecked = currentCheckedKeys.includes(item.id);
            
            return {
                title: editMode ? item.name : (
                    <>
                        {item.name}
                        {item.status === 1 && '（已禁用）'}
                        {!editMode && isChecked && (
                            <span style={{ color: '#1890ff', fontSize: '12px', marginLeft: '4px' }}>
                                ✓ 已选择
                            </span>
                        )}
                    </>
                ),
                key: item.id,
                value: item.id,
                disabled: item.is_protected === 1, // 禁用状态的部门不可选择
                children: item.children ? item.children.map(convertNode) : undefined,
            };
        };

        return data.map(convertNode);
    }, []);

    // 使用 useMemo 计算树数据，根据选中状态和编辑状态动态更新
    const computedTreeData = useMemo(() => {
        return transformTreeData(rawTreeData, checkedKeys, is_edit);
    }, [rawTreeData, checkedKeys, is_edit, transformTreeData]);


    // 暴露方法给父组件
    useImperativeHandle(ref, () => ({
        getData: () => {
            return getDataPermissionData();
        },
        validateForm: () => {
            return form.validateFields();
        },
        resetForm: () => {
            form.resetFields();
        },
        setFormData: (data) => {
            form.setFieldsValue(data);
        }
    }));


    // 获取表单数据
    const getDataPermissionData = useCallback(() => {
        const data = form.getFieldsValue();
        if (data.data_scope === 5) {
            data.data_scope_dept_ids = checkedKeys.join(',');
        }
        return data;
    }, [form, checkedKeys]);




    // 数据范围选项
    const dataScopeOptions = [
        { value: 1, label: '全部数据', description: '可访问所有数据，无限制' },
        { value: 2, label: '所在部门及以下', description: '可访问本部门及所有下级部门数据' },
        { value: 3, label: '所在部门', description: '仅可访问本部门数据' },
        { value: 4, label: '仅自己数据', description: '仅可访问自己创建的数据' },
        { value: 5, label: '自定义数据范围', description: '按选择的部门范围控制数据访问权限' },
    ];


    // 权限范围变更
    const handleScopeChange = (value) => {
        if (value !== 5 && isCustomScope) {
            setIsCustomScope(false);
            setCheckedKeys([]);
        } else if (value === 5) {
            setIsCustomScope(true);
        }
    };


    // 获取部门列表
    const getDepartmentList = async () => {

        const [err, result] = await adminApi.getDepartmentTree();
        if (err) {
            // message.error('获取部门列表失败')
        }
        if (result) {
            setRawTreeData(result.data); // 保存原始数据
        }
    }

    

    // 处理自定义范围部门数据
    const handleCustomScopeData = (data) => {
        if (!data || typeof data !== 'string') {return [];}
        return data.split(',').filter(id => id.trim() !== '').map(id => Number(id.trim()));
    }

    

    // 部门树选择事件 - 处理点击选中
    const onCheck = (checkedKeysValue) => {
        setCheckedKeys(checkedKeysValue);
    };

    return (

        <>
            <Form
                name="data_permission_form"
                form={form}
                initialValues={{ data_scope: 1}}
                // colon={!is_edit}
                autoComplete="off"
                // layout="inline"
                style={{ width: '100%' }}
                
            >
                <Form.Item name="data_scope" label="权限范围">
                    <Select onChange={handleScopeChange}>
                        {dataScopeOptions.map(option => (
                            <Select.Option key={option.value} value={option.value}>
                                {option.label}
                            </Select.Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item name="data_scope_dept_ids" label="部门范围" hidden>
                    <Input />
                </Form.Item>
            
                    
            </Form>
            {
                isCustomScope && (
            
                <Card title="自定义范围">
                    {
                        computedTreeData && computedTreeData.length > 0 ?<Tree
                            showLine
                            autoExpandParent={true}
                            defaultExpandAll={true}
                            checkable={is_edit}
                            treeData={computedTreeData}
                            checkedKeys={checkedKeys}
                            onCheck={onCheck}
                        />:<Empty />
                    }
                </Card>
                )
            }
        </>
    )
})


const areEqual = (prev, next) => {
    if (prev.is_edit !== next.is_edit) {return false;}
    if (prev.access_type !== next.access_type) {return false;}
    if (prev.scope !== next.scope) {return false;}
    if (prev.curstom_ids !== next.curstom_ids) {return false;}
    const prevIds = typeof prev.curstom_ids === 'string' ? prev.curstom_ids : (prev.curstom_ids || []).join(',');
    const nextIds = typeof next.curstom_ids === 'string' ? next.curstom_ids : (next.curstom_ids || []).join(',');
    if (prevIds !== nextIds) {return false;}
    return true;
};

export default memo(DataPermission, areEqual);
